var userService = require('../../services/userService');
var adminUserService = require('../../services/backoffice/backOffice-adminUserService');
var md5 = require('MD5');
var Audits = mongoose.model('backoffice_audits');
var cacheUtil = require('./cacheUtil');
var Users = mongoose.model('user');
var toolUtil = require('./toolUtil');
var adminUsers = mongoose.model('backoffice_adminusers');
var userDevice = mongoose.model('user_device_profile');
var Question = mongoose.model('question');
var neighbourActivity = mongoose.model('activity_neighbour');
var specialTopics = mongoose.model('system_specialTopics');
var qiniuUtil = require('./qiniuUtil');

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   start   */
var moment = require('moment');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   end   */

/**
 * 对每个消息记录消息的Audit日志;
 */
exports.doAudit = function (req, status) {
    var audit = new Audits();
    var tempStartDateTime = new Date(req.requestStartDataTime);
    var tempEndDateTime = new Date();
    audit.ip = req.ip;
    audit.userId = req.params.token;
    audit.RESTURL = req.url;
    audit.requestProcessedStatus = status;
    audit.startDateTime = tempStartDateTime;
    audit.endDateTime = tempEndDateTime;
    audit.elapsedMilliSeconds = tempEndDateTime.getTime() - tempStartDateTime.getTime();
    audit.save(function (err) {
        //if (err) {
        //    logger.error('Failed to save the audit information....!' + err.message);
        //}
    });
};

/**
 *  根据用户的对象ID,生成一个token
 *  把token缓冲到memCache中
 */

exports.generateAndCacheToken = function (userObjectId) {
    var token = userObjectId;
    //cacheUtil.cacheSet(token, userObjectId, function (err, result) {
    //    if (err) {
    //        logger.error('Error happened when token generation and caching for user - ' + userObjectId);
    //    } else {
    //        logger.debug('Successfully for token generation and caching for user - ' + userObjectId);
    //    }
    //}, userTokenExpireSeconds);
    adminUserService.adminUserFindByToken(token, function (err, user) {

        if (err) {
            logger.error('Exception happened when trying to find user based on user userId...!' + err.message);
        } else {
            if(user.communities != null ){
                user._doc.community = user.communities[0];
            }
            cacheUtil.cacheSet(token, JSON.stringify(user), function (err, result) {
                if (err) {
                    logger.error('Failed to cache the user by - ' + err.message);
                } else {
                    logger.debug('Succeeded to cache the user by - ' + token);
                }
            }, userDataCacheByTokenExpireSeconds);
        }
    });
    return token;
};

exports.generateAndCacheTokenForModerator = function (userObjectId) {
    var token = userObjectId;
    //var token = userObjectId +'-'+ new Date().getTime();
    //cacheUtil.cacheSet(token, userObjectId, function (err, result) {
    //    if (err) {
    //        logger.error('Error happened when token generation and caching for user - ' + userObjectId);
    //    } else {
    //        logger.debug('Successfully for token generation and caching for user - ' + userObjectId);
    //    }
    //}, userTokenExpireSeconds);
    return token;
};

exports.getAndCacheHuanXinToken = function (callback) {
    var key = 'huanXinToken';
    cacheUtil.cacheGet(key, function (err, result) {
        if (result == null) {
            var args = {
                data: huanxinOption,
                headers: {
                    "Content-Type": "application/json"
                }
            };
            restClient.post("http://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/token", args, function (data, response) {
                logger.debug(data);
                cacheUtil.cacheSet(key, data.access_token, function (err, result) {
                    if (err) {
                        logger.error('Failed to cache the huanxin token');
                    } else {
                        callback(null, data.access_token);
                    }
                }, data.expires_in - 3600);
            }).on('error', function (err) {
                logger.debug('error:' + err.stack);
            });
        } else {
            callback(null, result);
        }
    })
};

/**
 * 把请求消息放入到message Queue
 * 消息格式为：
 * httpMethod, URL, userID, bodyData, DateTime
 *
 */
exports.putMessageRequestMQ = function (message) {
    //mqConnection.publish('requestMessage', message);
};

exports.putMessageQAMQ = function (message) {
    if (enbalePush != null && enbalePush == 'Yes') {
        logger.info('push message to q.push.qa');
        mqConnection.publish('q.push.qa', message);
    }
};

exports.putMessageLogMQ = function (message) {
    mqConnection.publish('q.app.log', message);
};

/**
 * 往messageQueue中丢入需要向baidu推送的消息
 * 消息的格式为：
 * {
     "baiduToken":   "XXXX",
     "userObjId":    "XXX",
     "messageDesc":  "XXXX"  
  }
 *
 */
exports.putMessageBaiduPushMQ = function (message) {
    mqConnection.publish('baiduPushMessage', message);
};

exports.putMessageVerificationCodeMQ = function (message) {
    mqConnection.publish('verificationCodeMessage', message);

};

exports.putMessageLoginOrRegisterLogMQ = function (message) {
    mqConnection.publish('q.log.loginOrRegister', message);
};

exports.putMessageGetuiPushMQ = function (message) {
    mqConnection.publish('getuiPushMessage', message);
};
exports.putMessageTransmissionPushMQ = function (message) {
    mqConnection.publish('q.push.transmission', message);
};
exports.putMessageActivityMQ = function (message) {
    mqConnection.publish('q.activity.msg.push', message);
};
exports.putMessageCommunityCalcAroundMQ = function (message) {
    mqConnection.publish('q.community.around', message);
};

exports.putMessageTagPushMQ = function (message) {
    mqConnection.publish('q.business.push', message);
};

// 发送短信统一接口
exports.putMessageSMS = function (phone, content,smsType) {
    var data = {
        "phoneNum":phone,
        "content":content
    };
    if(!smsType) {
        data.smsType = 2;
    }
    logger.debug(data);
    mqConnection.publish('q.msg.publish', data);
};

// 异步加情值
exports.addScoreMessage = function (user, role, type) {


    var arg = {
        userId: user,
        userRole: 1,
        userActionType: type
    };

    arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
    logger.debug(arg);
    scoreProxy.invoke('addScore', [arg], function (err, reply) {
        try {
            logger.debug(reply);

            var data = JSON.parse(decodeURIComponent(reply));
            if (err) {
                logger.error('hessianInvokeAddScore-----2' + err.message);
                //callbackInner(null);
            } else if (data.status != 0) {
                logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                //callbackInner(null);
            } else {
                //callbackInner(null);
            }
        } catch (e) {
            logger.error('hessianInvokeAddScore---4' + e);
            //callbackInner(e);
        }
    });
};



exports.pushServiceId = function (communities, serviceId) {
    var content = {
        f: 5,
        q: serviceId
    };
    var pushData = {
        tags: communities,
        content: content,
        pushApns: 'no'
    };
    mqConnection.publish('q.push.tag', pushData);
};

exports.putMessageBusinessMQ = function (message) {
    mqConnection.publish('q.business.push', message);
};

/**
 * 根据token去获取对应的用户objId是多少
 */
exports.getUserObjIdByToken = function (userObjId) {
    return userObjId;
};

exports.setUserByToken = function (token) {
    userService.findByIdService(token, function (err, user) {
        if (err) {
            logger.error('Exception happened when trying to find user based on user userId...!' + err.message);
        } else {
            cacheUtil.cacheSet(token, JSON.stringify(user), function (err, result) {
                if (err) {
                    logger.error('Failed to cache the user by - ' + err.message);
                } else {
                    logger.debug('Succeeded to cache the user by - ' + token);
                }
            }, userDataCacheByTokenExpireSeconds);
        }
    })
};

exports.getUserByToken = function (token, callback) {
    cacheUtil.cacheGet(token, function (err, result) {
        if (err) {
            logger.error('Failed to get the user by - ' + token);
            callback(err, null);
        } else {
            try {
                var user = JSON.parse(result);
                if (user == null) {
                    var msg = {
                        "message": noUserErrMessage
                    };
                    callback(msg, null);
                } else if (user.community == null) {
                    var msg = {
                        "message": '未设置小区'
                    };
                    callback(msg, user);
                } else {
                    callback(null, user);
                }
            } catch (e) {
                logger.error(e);
                var msg = {
                    "message": noUserErrMessage
                };
                callback(msg, null);
            }
        }
    });
};

exports.md5Validate = function (deviceId, body) {
    var reqMd5 = body.md5;
    delete body.md5;
    body['deviceId'] = deviceId;
    body['app_key'] = App_key;
    var keys = [];
    for (var key in body) {
        if (typeof body[key] == 'string')
            keys.push(key);
    }
    keys.sort();
    var str = '';
    keys.forEach(function (key) {
        str += body[key];
    });

    logger.info(str);
    logger.info(nowMd5);
    if (reqMd5 == nowMd5) {
        return true;
    } else {
        return false;
    }
};

/**
 * 根据userId获取baiduPushToken
 */

exports.getPushTokenByUserId = function (userId, callback) {
    userService.findPushTokenService(userId, function (err, result) {
        if (err) {
            callback(err, null)
        } else {
            if (result != null) {
                callback(null, result.baiduMessagePushingToken);
            }
        }
    })
};

/**
 * 根据手机号去生成验验证吗，保存在缓冲中；
 */
exports.generateVerificationCode = function (mobilePhone, key) {

    var Num = '';
    for (var j = 0; j < 4; j++) {
        var ran = Math.floor(Math.random() * 10);
        if (j == 0) {
            while (ran == 0) {
                ran = Math.floor(Math.random() * 10);
            }
        }
        Num += ran;
    }
    cacheUtil.cacheSet(key, Num, function (err, result) {
        if (err) {
            logger.error('Failed to generate the verification code for - ' + mobilePhone);
        } else {
            logger.debug('Succeeded to generate the verification code for - ' + mobilePhone);
        }
    }, verificationCodeExpiredSeconds);
    return Num;
};


/**
 * 图片上传, 最多10张图片
 * 存放在/public/tempImages/objID/timestamp/objID+timestamp+fileName
 * 返回的是一个图片的存放URL的数组
 */

var fs = require('fs');
var async = require('async');

exports.uploadImageService = function (objectName, id, req, callback) {

    async.series([
        function (callbackInner) {
            if (req.files.image1 != null) {
                var imageName1 = req.files.image1.name;
                var imagePath1 = req.files.image1.path;

                qiniuUtil.uploadFile(imagePath1, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath1);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image2 != null) {
                var imageName2 = req.files.image2.name;
                var imagePath2 = req.files.image2.path;

                qiniuUtil.uploadFile(imagePath2, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath2);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image3 != null) {
                var imageName3 = req.files.image3.name;
                var imagePath3 = req.files.image3.path;
                qiniuUtil.uploadFile(imagePath3, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath3);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image4 != null) {
                var imageName4 = req.files.image4.name;
                var imagePath4 = req.files.image4.path;
                qiniuUtil.uploadFile(imagePath4, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath4);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image5 != null) {
                var imageName5 = req.files.image5.name;
                var imagePath5 = req.files.image5.path;
                qiniuUtil.uploadFile(imagePath5, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath5);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image6 != null) {
                var imageName6 = req.files.image6.name;
                var imagePath6 = req.files.image6.path;
                qiniuUtil.uploadFile(imagePath6, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath6);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image7 != null) {
                var imageName7 = req.files.image7.name;
                var imagePath7 = req.files.image7.path;
                qiniuUtil.uploadFile(imagePath7, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath7);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image8 != null) {
                var imageName8 = req.files.image8.name;
                var imagePath8 = req.files.image8.path;
                qiniuUtil.uploadFile(imagePath8, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath8);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image9 != null) {
                var imageName9 = req.files.image9.name;
                var imagePath9 = req.files.image9.path;
                qiniuUtil.uploadFile(imagePath9, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath9);
                });
            }
            else {
                return callbackInner(null, null);
            }
        },

        function (callbackInner) {
            if (req.files.image10 != null) {
                var imageName10 = req.files.image10.name;
                var imagePath10 = req.files.image10.path;
                qiniuUtil.uploadFile(imagePath10, function(err,result){
                    callbackInner(err,result);
                    fs.unlink(imagePath10);
                });
            }
            else {
                return callbackInner(null, null);
            }
        }
    ], callback);
};


exports.getRandomNumArray = function (length, Range) {
    var num = [];
    for (var i = 0; i < length; i++) {
        var val = Math.ceil(Math.random() * Range - 1);
        var isEqu = false;
        for (var idx in num) {
            if (num[idx] == val) {
                isEqu = true;
                break;
            }
        }
        if (isEqu)
            i--;
        else
            num[num.length] = val;
    }
    return num;
};

/**
 * 字符串转16进制
 * @param str
 * @returns {string}
 */
exports.stringToHex = function (str) {
    var val = "";
    for (var i = 0; i < str.length; i++) {
        var v = str.charCodeAt(i).toString(16);
        while (v.length < 4) {
            v = 0 + v;
        }
        val += v;
    }
    return val;
};

/**
 * 判断当前时间是否在某一时间段
 * @param beginTime
 * @param endTime
 * @returns {boolean}
 */
exports.time_range = function (beginTime, endTime) {
    var strb = beginTime.split(":");
    if (strb.length != 2) {
        return false;
    }
    var stre = endTime.split(":");
    if (stre.length != 2) {
        return false;
    }
    var b = new Date();
    var e = new Date();
    var n = new Date();

    b.setHours(strb[0]);
    b.setMinutes(strb[1]);
    e.setHours(stre[0]);
    e.setMinutes(stre[1]);

    if (b.getTime() - e.getTime() >= 0) {
        if (n.getTime() - b.getTime() > 0 || n.getTime() - e.getTime() < 0) {
            return true;
        } else {
            return false;
        }
    } else {
        if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
            return true;
        } else {
            return false;
        }
    }
};


/**
 *  获取抽奖号码
 */
exports.generateLotteryTickets = function (key, callback) {
    redisClient.smembers(key, function (err, value) {
        if (err) throw(err);
        var pool = key + ':pool';
        var discard = key + ':discard';
        if (value.length < 100) {
            redisClient.sunion([key, pool, discard], function (err, value) {
                if (err) throw(err);
                var ran = getLotteryTickets(value, 500);
                redisClient.sadd(key, ran, function (err, result) {
                    redisClient.spop(key, function (err, value) {
                        if (value != null) {
                            redisClient.sadd(pool, value);
                            callback(err, value)
                        }
                    });
                });
            })
        } else {
            redisClient.spop(key, function (err, value) {
                if (value != null) {
                    redisClient.sadd(pool, value);
                    callback(err, value)
                }
            });
        }
    })
};

function getLotteryTickets(c, length) {
    var num = [];
    for (var i = 0; i < length; i++) {

        var val = '';
        for (var j = 0; j < 6; j++) {
            var ran = Math.floor(Math.random() * 10);
            if (j == 0) {
                while (ran == 0) {
                    ran = Math.floor(Math.random() * 10);
                }
            }
            val += ran;
        }
        var isEqu = false;
        for (var idx in num) {
            if (num[idx] == val) {
                isEqu = true;
                break;
            }
        }
        if (contains(c, val)) {
            isEqu = true;
        }
        if (isEqu)
            i--;
        else
            num[num.length] = val;
    }
    return num;
}

function contains(array, obj) {
    var i = array.length;
    while (i--) {
        if (array[i] === obj) {
            return true;
        }
    }
    return false;
}

/**
 * 小6客服发消息
 * @param user
 * @param message
 */
exports.pushCustomerServiceMessage = function (user, message) {
    toolUtil.getAndCacheHuanXinToken(function (err, token) {

        userDevice.findOne({userId: user._id}, 'vCode', function (err, version) {
            if (version != null && version.vCode != null && version.vCode == appVersionCode) {
                toolUtil.getCustomerServiceByCommunityId(user.community._id, function (err, service) {
                    var args = {
                        data: {
                            "target_type": "users",
                            "target": [user.huanxinUserName],
                            "msg": {
                                "type": "txt",
                                "msg": message
                            },
                            "from": service.huanxinUserName,
                            "ext": {           //扩展属性, 由app自己定义.可以没有这个字段，但是如果有，值不能是“ext:null“这种形式，否则出错
                                "nickName": "小6客服",
                                "avatar": service.images[0].imageURL,
                                "objId": service._id
                            }
                        },
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": "Bearer " + token
                        }
                    };
                    restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/messages", args, function (data, response) {
                        logger.debug(data);
                    }).on('error', function (err) {
                        logger.error('sendMessageByCustomService' + err.message);
                    });
                })
            } else if (version != null && version.vCode != null && version.vCode > appVersionCode) {
                Users.findOne({'huanxinUserName': '66customerservice'}, '_id images huanxinUserName', function (err, result) {
                    var args = {
                        data: {
                            "target_type": "users",
                            "target": [user.huanxinUserName],
                            "msg": {
                                "type": "txt",
                                "msg": message
                            },
                            "from": 'superservice',
                            "ext": {           //扩展属性, 由app自己定义.可以没有这个字段，但是如果有，值不能是“ext:null“这种形式，否则出错
                                "nickName": "小6客服",
                                "avatar": result.images[0].imageURL,
                                "objId": result._id
                            }
                        },
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": "Bearer " + token
                        }
                    };
                    restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/messages", args, function (data, response) {
                        logger.debug(data);
                    }).on('error', function (err) {
                        logger.error('sendMessageByCustomService' + err.message);
                    });
                });
            } else {
                Users.findOne({'huanxinUserName': '66customerservice'}, '_id images huanxinUserName', function (err, result) {
                    var args = {
                        data: {
                            "target_type": "users",
                            "target": [user.huanxinUserName],
                            "msg": {
                                "type": "txt",
                                "msg": message
                            },
                            "from": result.huanxinUserName,
                            "ext": {           //扩展属性, 由app自己定义.可以没有这个字段，但是如果有，值不能是“ext:null“这种形式，否则出错
                                "nickName": "小6客服",
                                "avatar": result.images[0].imageURL,
                                "objId": result._id
                            }
                        },
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": "Bearer " + token
                        }
                    };
                    restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/messages", args, function (data, response) {
                        logger.debug(data);
                    }).on('error', function (err) {
                        logger.error('sendMessageByCustomService' + err.message);
                    });
                });
            }
        });
    });
};

exports.deleteImage = function (fileIds) {
    async.each(fileIds, function (fileId, callbackInner) {
        if (fileId != null) {
            var id = fileId.substr(1);
            fdfsClient.del(id, callbackInner);
        } else {
            callbackInner();
        }
    }, function (err) {
        logger.debug('----deleteImage');
    })
};

exports.hessianInvokeAddScore = function (token, action, score, callback, vCode) {

    Users.findOne({_id: token + ''}, function (err, user) {

        if (err) {
            logger.error('hessianInvokeAddScore----1' + err.message);
            callback(null);
        //} else if (!user.authenticationStatus) {
        //    logger.error('hessianInvokeAddScore---未认证用户无法加积分');
        //    callback(null);
        } else {
            var userRole = 1;

            if (user.userType == 'talent') {
                userRole = 2;
            }

            var arg = {
                userId: user._id + '',
                userRole: userRole,
                userActionType: action
            };

            if (vCode != null) {
                arg.vCode = vCode
            }

            if (score != null) {
                arg.addScore = score
            }

            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                try {
                    if (err) {
                        logger.error('hessianInvokeAddScore-----2' + err.message);
                        callback(null);
                    } else {
                        var data = JSON.parse(decodeURIComponent(reply));
                        if (data.status != 0) {
                            logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                            callback(null);
                        } else {
                            callback(data.data);
                        }
                    }
                } catch (e) {
                    logger.error('hessianInvokeAddScore---4' + e);
                    callback(null);
                }
            });

        }
    });
};


/**
 * 获取邀请码
 * @param callback
 */
exports.getInvitationCode = function (callback) {
    var codeKey = 'app:invitation:code';
    var indexKey = 'app:invitation:index';

    redisClient.scard(codeKey, function (err, count) {
        if (err) throw(err);
        if (count < 100) {
            redisClient.get(indexKey, function (err, value) {
                var index = value == null ? '10000' : value;
                if (index == 'over') {
                    redisClient.spop(codeKey, callback);
                } else {
                    redisClient.sadd(codeKey, createInvitationCodeByIndex(index), function (err, result) {
                        if (index == '90000') {
                            redisClient.set(indexKey, 'over');
                        } else {
                            redisClient.set(indexKey, Number(index) + 10000);
                        }
                        redisClient.spop(codeKey, callback);
                    });
                }
            });
        } else {
            redisClient.spop(codeKey, callback);
        }
    })
};

function createInvitationCodeByIndex(index) {
    index = Number(index);
    var codeArray = [];
    for (var i = index; i <= index + 9999; i++) {
        codeArray.push(i);
    }
    return codeArray;
}

exports.getPromotionCode = function (length, callback) {
    var key = 'app:promotion:code';

    redisClient.smembers(key, function (err, value) {
        var ran = getLotteryTickets(value, length);
        redisClient.sadd(key, ran, function (err, result) {
            callback(err, ran);
        });
    });
};

/**
 * 根据小区id获取客服信息
 * @param communityId
 * @param callback
 */
exports.getCustomerServiceByCommunityId = function (communityId, callback) {

    adminUsers.findOne({
        communities: communityId,
        role: 'Service',
        signed: true
    }).populate('appuser', 'images nickName huanxinUserName')
        .exec(function (err, result) {
            if (result != null) {
                callback(err, result.appuser);
            } else {
                Users.findOne({huanxinUserName: '66customerservice'}, 'images nickName huanxinUserName', function (err, result) {
                    callback(err, result);
                })
            }
        })
};

exports.filteringSensitiveWords = function (id, replyId, replyDesc, category) {
    restClient.get('http://' + RecommendHost + ':8002?data=' + replyDesc, function (data, response) {
        if (response.statusCode == 200 && data != null && data != 'unknown' && data != '') {
            try {
                if (typeof data == 'string') {
                    data = JSON.parse(data)
                }
                var sensitive = data.sensitive;
                if (sensitive != null) {
                    replyDesc = sensitive;

                    if (category == 'question') {
                        Question.update({
                            _id: id,
                            'replies._id': replyId
                        }, {'replies.$.replyDesc': replyDesc}).exec();
                    } else if (category == 'activity') {
                        neighbourActivity.update({
                            _id: id,
                            'replies._id': replyId
                        }, {'replies.$.replyDesc': replyDesc}).exec();
                    } else if (category == 'topic') {
                        specialTopics.update({
                            _id: id,
                            'comments._id': replyId
                        }, {'comments.$.commentDesc': replyDesc}).exec();
                    }
                }
            } catch (e) {
                logger.error('filteringSensitiveWords----' + data);
            }
        }
    });
};


exports.transformNumber = function (number) {
    return number + '';
};

//根据参数名获取url参数值
exports.getQueryString = function(url, name) {
    var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)", "i");
    var r = url.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   start   */
// 根据指定区间返回每天的数组(数组大小比实际天数多一天)
exports.getArrayDateByStartEndDate = function(startDateSelect, endDateSelect) {

    var endDate = moment(endDateSelect, "YYYY-MM-DD").add(1, "days").format();
    var tempDate = moment(startDateSelect, "YYYY-MM-DD").format();

    var flag = true;
    var dateArray = [];
    while(flag) {
        if(tempDate <= endDate) {
            dateArray.push(tempDate);
            tempDate = moment(tempDate, "YYYY-MM-DD").add(1, "days").format();
        } else {
            flag = false;
        }
    }
    return dateArray;
};

// 根据指定区间返回每天的数组(数组大小与实际天数一样)
exports.getArrayDateByStartEndDateMin = function(startDateSelect, endDateSelect) {

    var endDate = moment(endDateSelect, "YYYY-MM-DD").format();
    var tempDate = moment(startDateSelect, "YYYY-MM-DD").format();

    var flag = true;
    var dateArray = [];
    while(flag) {
        if(tempDate <= endDate) {
            dateArray.push(tempDate);
            tempDate = moment(tempDate, "YYYY-MM-DD").add(1, "days").format();
        } else {
            flag = false;
        }
    }
    return dateArray;
};

/*  宝宝树66小区sprint4    add   66后台订单总佣金.查询 wangcan  20171030  start   */
// 根据指定区间返回每天的数组(数组大小与实际天数一样)
exports.getDateArrByStartEndDate = function(startDateSelect, endDateSelect) {

    var endDate = moment(endDateSelect).format();
    var tempDate = moment(startDateSelect).format();

    var flag = true;
    var dateArray = [];
    while(flag) {
        if(tempDate <= endDate) {
            dateArray.push(tempDate);
            tempDate = moment(tempDate).add(1, "days").format();
        } else {
            flag = false;
        }
    }
    return dateArray;
};
/*  宝宝树66小区sprint4    add   66后台订单总佣金.查询 wangcan  20171030  end   */

/*  宝宝树66小区sprint4    add   66后台订单总佣金.查询 wangcan  20171110  start   */
// 去除数组中重复的数据
exports.arrayDislodgeRepeat = function (tempArr) {
    var retArr = [];
    var tempObj = {};
    for (var i = 0, length = tempArr.length; i < length; i++) {
        if (!tempObj[tempArr[i].toString()]) {
            retArr.push(tempArr[i]);
            tempObj[tempArr[i].toString()] = 1;
        }
    }
    return retArr;
};
/*  宝宝树66小区sprint4    add   66后台订单总佣金.查询 wangcan  20171110  end   */

// 数组内所有数据求和
exports.getNumberSumByArray = function(numberArray) {
    var count = 0;
    async.eachSeries(numberArray, function (nunmber, callbackInner) {
        count += nunmber;
        callbackInner(false);
    }, function (err) {
    });
    return count;
};

exports.getMtSignParams = function(starttime, endtime, pageno, pagesize, signtime) {
    // MD5(signtime_starttime_endtime_pageno_pagesize_key) -> 大写
    var mtKey = "iambabytreekey!@#$%^&*()";
    var tempSign = signtime + '_' + starttime + '_' + endtime + '_' + pageno + '_' + pagesize + '_' + mtKey;

    return  '&starttime='+ starttime +
        '&endtime='+ endtime +
        '&pageno='+ pageno +
        '&pagesize='+ pagesize +
        '&signtime='+ signtime +
        '&sign='+ md5(tempSign).toUpperCase();
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   end   */

/*  宝宝树66小区五次改造-66订单退款状态    add   guo.xiaomin  20171120   start   */
exports.getRefundStatusSignParams = function(subList, signtime) {
    // MD5(signtime_codes_key) -> 大写
    var mtKey = "iambabytreekey!@#$%^&*()";
    var codes = subList.toString(); // 数组变字符串
    var tempSign = signtime + '_' + codes + '_' + mtKey;

    return  '&codes='+ codes +
        '&signtime='+ signtime +
        '&sign='+ md5(tempSign).toUpperCase();
};
/*  宝宝树66小区五次改造-66订单退款状态    add   guo.xiaomin  20171120   end   */

/*  宝宝树66小区sprint4    add   66后台结算佣金管理.计算佣金比例 guoxiaomin  20171027  start   */
exports.getCommissionPercent = function (orderInfo) {
    // 销售类型 自营,非自营
    var itemSaleType = orderInfo.itemSaleType;
    // 是否海淘商品 否,是
    var wavesSign = orderInfo.wavesSign;
    // 是否标品 非标品,标品
    var standard = orderInfo.standard;
    var commissionPercent = 0;
    if(wavesSign == "是") {
        if(standard == "非标品") {
            // 海淘非标品佣金4%
            commissionPercent = 0.04;
        } else {
            // 海淘非标品佣金1.5%
            commissionPercent = 0.015;
        }
    } else {
        if(itemSaleType == '非自营') {
            if(standard == "非标品") {
                // 国内非标品佣金7%
                commissionPercent = 0.07;
            } else {
                // 国内标品佣金1.5%
                commissionPercent = 0.015;
            }
        } else {
            commissionPercent = 0;
        }
    }
    return commissionPercent;
};

exports.getCommissionPercentName = function (orderInfo) {
    var commissionPercentName = {};
    var commissionPercent = 0;
    var commissionName = null;
    // 销售类型 自营,非自营
    var itemSaleType = orderInfo.itemSaleType;
    // 是否海淘商品 否,是
    var wavesSign = orderInfo.wavesSign;
    // 是否标品 非标品,标品
    var standard = orderInfo.standard;
    // 先判断自营非自营，在判断其他
    //销售类型 0-自营 1-非自营
    if(itemSaleType == 0) {
        commissionPercent = 0;
        commissionName = "自营-无佣金";
    } else {
        //是否标品 0 非标品  1标品  -1未设置
        if (standard == 1) {
            //是否海淘商品,1-否，2-是，默认1
            if (wavesSign == 2) {
                // 海淘标品佣金1.5%
                commissionPercent = 0.015;
                commissionName = "海淘标品-非自营";
            } else {
                // 国内标品佣金1.5%
                commissionPercent = 0.015;
                commissionName = "国内标品-非自营";
            }

        } else if (standard == 0) {
            if (wavesSign == 2) {
                // 海淘非标品佣金4%
                commissionPercent = 0.04;
                commissionName = "海淘非标品-非自营";
            } else {
                // 国内非标品佣金7%
                commissionPercent = 0.07;
                commissionName = "国内非标品-非自营";
            }
        }
    }
    /* 宝宝树66小区 sprint5 1月1日后拼团无佣金 add guoxiaomin 20171212 start */
    if(exports.isOrderTimeBiggerThanCommissionZeroStartDate(new Date(orderInfo.order_time).getTime())) {
        commissionPercent = 0;
        commissionName += "(*1)";
    }
    /* 宝宝树66小区 sprint5 1月1日后拼团无佣金 add guoxiaomin 20171212 end */

    commissionPercentName.commissionPercent = commissionPercent;
    commissionPercentName.commissionName = commissionName;
    return commissionPercentName;
};

/* 宝宝树66小区 sprint5 1月1日后拼团无佣金 add guoxiaomin 20171212 start */
exports.isOrderTimeBiggerThanCommissionZeroStartDate = function(orderTime) {
    // 全局参数
    var tempCommissionZeroStartDate = global.commissionZeroStartDate;
    if(!tempCommissionZeroStartDate) {
        logger.error("全局参数没有commissionZeroStartDate，请修改配置文件...");
        tempCommissionZeroStartDate = '2018-01-01';
    }
    var temp = new Date(moment(tempCommissionZeroStartDate, "YYYY-MM-DD").format()).getTime();
    if(orderTime > temp) {
        logger.debug("isNowBiggerThanCommissionZeroStartDate..." + true);
        return true;
    } else {
        logger.debug("isNowBiggerThanCommissionZeroStartDate..." + false);
        return false;
    }
};
/* 宝宝树66小区 sprint5 1月1日后拼团无佣金 add guoxiaomin 20171212 end */

// 销售类型 0-自营 1-非自营
exports.getItemSaleTypeName = function (itemSaleType) {
    if(itemSaleType == 0) {
        return "自营";
    } else if(itemSaleType == 1) {
        return "非自营";
    } else {
        return null;
    }
};

//是否海淘商品,1-否，2-是，默认1
exports.getWavesSignName = function (wavesSign) {
    if(wavesSign == 1) {
        return "非海淘";
    } else if(wavesSign == 2) {
        return "海淘";
    } else {
        return null;
    }
};

// 是否标品 0 非标品  1标品  -1未设置
exports.getStandardName = function (standard) {
    if(standard == 0) {
        return "非标品";
    } else if(standard == 1) {
        return "标品";
    } else if(standard == -1) {
        return "未设置";
    } else {
        return null;
    }
};

exports.get4CommissionPrice = function (commissionPrice, status) {
    if(status >= 3 && status <= 6) {
        return commissionPrice;
    } else {
        return 0;
    }
};

exports.get4CommissionUser = function (commissionUser, status) {
    if(status >= 3) {
        // 下单成功过的人,都算(可退款)
        return commissionUser;
    } else {
        // 未下单成功
        return null;
    }
};

exports.isNotEmpty = function (str) {
    if(str != undefined && str != null) {
        return true;
    } else {
        return false;
    }
};
exports.isNotUndefined = function (str) {
    if(str != undefined) {
        return true;
    } else {
        return false;
    }
};
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.计算佣金比例 guoxiaomin  20171027  end   */
/*  宝宝树66小区sprint4    add   66后台结算佣金管理.结算状态 guoxiaomin  20171027  end   */
exports.getCommissionStatus = function (order,userId) {
    var result = "";
    // 结算状态
    if ((order._doc.shareCommissionUser
        &&order._doc.shareCommissionUser._id.toString() == userId)
        || (order._doc.selfPurchaseUser
        && order._doc.selfPurchaseUser._id.toString()  == userId)
        || (order._doc.communityCommissionUser
        && order._doc.communityCommissionUser._id.toString()  == userId)) {
        // 本单结算类型
        if (order._doc.balanceStatus == 0) {
            result="未处理";
        } else if (order._doc.balanceStatus == 1) {
            result="已粗算";
        } else if (order._doc.balanceStatus == 2) {
            result="已精算";
        } else if (order._doc.balanceStatus == 3) {
            result="已结算";
        } else if (order._doc.balanceStatus == 4) {
            result="已精算";
        } else if (order._doc.balanceStatus == 5) {
            result="已结算";
        }
    } else {
        // 提出结算类型
        if (order._doc.balanceStatus == 0) {
            result="未处理";
        } else if (order._doc.balanceStatus == 1) {
            result="已粗算";
        } else if (order._doc.balanceStatus == 2) {
            result="已精算";
        } else if (order._doc.balanceStatus == 3) {
            result="已精算";
        } else if (order._doc.balanceStatus == 4) {
            result="已结算";
        } else if (order._doc.balanceStatus == 5) {
            result="已结算";
        }
    }
    return result;
};

// 结算状态 1:已粗算，2:已精算，3:本单结算，4:提成结算，5::全部结算，0:初始值（4种）
exports.getBalanceStatusByName = function (balanceStatusName) {
    if(balanceStatusName == '已粗算') {
        return 1;
    } else if(balanceStatusName == '已精算') {
        return 2;
    } else if(balanceStatusName == '本单结算') {
        return 3;
    } else if(balanceStatusName == '提成结算') {
        return 4;
    } else if(balanceStatusName == '全部结算') {
        return 5;
    } else {
        return 0;
    }
};

/* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
// 结算状态 1:已粗算，2:已精算，3:本单结算，4:提成结算，5::全部结算，0:初始值（4种）
exports.getNameByBalanceStatus = function (balanceStatus) {
    if(balanceStatus == 1) {
        return '已粗算';
    } else if(balanceStatus == 2) {
        return '已精算';
    } else if(balanceStatus == 3) {
        return '本单结算';
    } else if(balanceStatus == 4) {
        return '提成结算';
    } else if(balanceStatus == 5) {
        return '全部结算';
    } else {
        return '初始值';
    }
};

// 订单状态: 已取消-0,新建-1,待支付-2,拣货中-3,待发货-4,待收货-5,已收货-6,申请取消-8,取消中（等第三方确认）-9,退款完成-100
exports.getNameByStatus = function (status) {
    if(status == 1) {
        return '新建';
    } else if(status == 2) {
        return '待支付';
    } else if(status == 3) {
        return '拣货中';
    } else if(status == 4) {
        return '待发货';
    } else if(status == 5) {
        return '待收货';
    } else if (status == 6) {
        return '已收货';
    } else if (status == 8) {
        return '申请取消';
    } else if (status == 9) {
        return '取消中';
    } else if (status == 100) {
        return '退款完成';
    } else {
        return '已取消';
    }
};
/* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */

exports.getCommissionUserFlag = function (findResult, uid) {
    var flag = null;
    if(!findResult) {
        logger.debug("flag = null");
        flag = null;
    } else {
        var shareCommissionUser = findResult.shareCommissionUser;
        var selfPurchaseUser = findResult.selfPurchaseUser;
        var communityCommissionUser = findResult.communityCommissionUser;
        var inviterCommissionUser = findResult.inviterCommissionUser;
        var inviterFlag = false;
        var sscFlag = false;
        var inviterUser = null;
        var sscUser = null;
        if(inviterCommissionUser) {
            logger.debug("inviterFlag = true");
            inviterFlag = true;
            inviterUser = inviterCommissionUser.toString();
        }
        if(shareCommissionUser || selfPurchaseUser || communityCommissionUser) {
            logger.debug("sscFlag = true");
            sscFlag = true;
            if(shareCommissionUser) {
                sscUser = shareCommissionUser.toString();
            } else if (selfPurchaseUser) {
                sscUser = selfPurchaseUser.toString();
            } else if (communityCommissionUser) {
                sscUser = communityCommissionUser.toString();
            }
        }
        if(inviterFlag && sscFlag) {
            logger.debug("inviterFlag && sscFlag");
            if(uid == inviterUser) {
                flag = 4;
            } else if(uid == sscUser) {
                flag = 3;
            } else {
                // 异常:0
            }
        } else if (inviterFlag && !sscFlag) {
            logger.debug("inviterFlag && !sscFlag");
            if(uid == inviterUser) {
                flag = 5;
            } else {
                // 异常:0
            }
        } else if (!inviterFlag && sscFlag) {
            logger.debug("!inviterFlag && sscFlag");
            if(uid == sscUser) {
                flag = 5;
            } else {
                // 异常:0
            }
        } else {
            logger.debug("else");
            // 异常:0
        }
    }
    return flag;
};

/*  宝宝树66小区sprint4    add   66后台结算佣金管理.结算状态 guoxiaomin  20171027  end   */

/*  宝宝树66小区sprint5    add   自购、分享、小区、团队 guoxiaomin  20171208  start   */
exports.getShareSelfCommunityInviterType = function (shareCommissionUser, selfPurchaseUser, communityCommissionUser, inviterCommissionUser) {
    var str = "";
    // 自购、分享、小区、团队
    if(shareCommissionUser) {
        str = "分享";
    } else if (selfPurchaseUser) {
        str = "自购";
    } else if (communityCommissionUser) {
        str = "小区";
    }
    if(inviterCommissionUser) {
        str += " 团队";
    }
    return str;
};
/*  宝宝树66小区sprint5    add   自购、分享、小区、团队 guoxiaomin  20171208  end   */